package cn.suimg.neo4j.config;

import cn.suimg.neo4j.annotation.DynamicQuery;
import cn.suimg.neo4j.graph.NeoGraph;
import lombok.extern.slf4j.Slf4j;
import org.neo4j.ogm.annotation.NodeEntity;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.util.ClassUtils;

import java.io.IOException;

import static cn.suimg.neo4j.config.Constant.*;

@Slf4j
@Configuration
public class WebConfig {


    @Bean
    @SuppressWarnings("unchecked")
    public Object initGraphMapping(){
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        final String BASE_PACKAGE = "cn.suimg.neo4j.graph";
        final String RESOURCE_PATTERN = "/*.class";
        try {
            String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(BASE_PACKAGE) + RESOURCE_PATTERN;
            Resource[] resources = resourcePatternResolver.getResources(pattern);
            MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(resourcePatternResolver);
            for (Resource resource : resources) {
                MetadataReader reader = readerFactory.getMetadataReader(resource);
                String classname = reader.getClassMetadata().getClassName();
                Class<?> clazz = Class.forName(classname);
                if (clazz.isAnnotationPresent(DynamicQuery.class)) {
                    NodeEntity nodeEntity = clazz.getAnnotation(NodeEntity.class);
                    String labelName = nodeEntity.label();
                    String clazzName = classname.substring(classname.lastIndexOf(".") + 1);
                    String graphName = clazzName.substring(0,1).toLowerCase() + clazzName.substring(1);
                    LABEL_2_GRAPH_MAPPING.put(labelName,graphName);
                    DYNAMIC_QUERY_CLASS_MAPPING.put(graphName,(Class<? extends NeoGraph>)clazz);
                }
            }
        } catch (IOException | ClassNotFoundException e) {
            log.error("initGraphMapping error",e);
        }
        return null;
    }

}
